/*
 * Copyright (c) 2018-2999 九五云信息科技有限公司 All rights reserved.
 *
 * https://www.gz-yami.com/
 *
 */

package com.yami.shop.groupbuy.multishop.controller;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yami.shop.bean.enums.ProdStatusEnums;
import com.yami.shop.bean.enums.ProdType;
import com.yami.shop.bean.model.Product;
import com.yami.shop.bean.param.ProductParam;
import com.yami.shop.common.annotation.SysLog;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.i18n.I18nMessage;
import com.yami.shop.common.i18n.LanguageEnum;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.groupbuy.comment.api.dto.ApiGroupActivityDto;
import com.yami.shop.groupbuy.comment.dto.GroupProdAndSkuListDto;
import com.yami.shop.groupbuy.comment.dto.GroupProdDto;
import com.yami.shop.groupbuy.comment.enums.ActivityStatusEnum;
import com.yami.shop.groupbuy.comment.enums.GroupProdStatusEnum;
import com.yami.shop.groupbuy.comment.model.GroupActivity;
import com.yami.shop.groupbuy.comment.model.GroupProd;
import com.yami.shop.groupbuy.comment.param.GroupProdParam;
import com.yami.shop.groupbuy.comment.service.GroupActivityService;
import com.yami.shop.groupbuy.comment.service.GroupProdService;
import com.yami.shop.security.multishop.util.SecurityUtils;
import com.yami.shop.service.ProductService;
import lombok.RequiredArgsConstructor;
import ma.glasnost.orika.MapperFacade;
import org.springframework.context.ApplicationContext;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.Objects;

/**
 * 拼团活动商品表
 *
 * @author LGH
 * @date 2019-08-27 17:55:57
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/group/prod")
public class GroupProdController {

    private final GroupProdService groupProdService;
    private final ProductService productService;
    private final MapperFacade mapperFacade;
    private final GroupActivityService groupActivityService;

    /**
     * 分页查询
     *
     * @param page      分页对象
     * @param groupProd 拼团活动商品表
     * @return 分页数据
     */
    @GetMapping("/page")
    public ResponseEntity<IPage<GroupProdDto>> getGroupProdPage(PageParam<GroupProd> page, GroupProd groupProd) {
        Long shopId = SecurityUtils.getShopUser().getShopId();
        groupProd.setShopId(shopId);
        IPage<GroupProdDto> groupProdIPage = groupProdService.getGroupProdPage(page, groupProd);
        return ResponseEntity.ok(groupProdIPage);
    }


    /**
     * 通过id查询拼团活动商品表
     *
     * @param groupProdId id
     * @return 单个数据
     */
    @GetMapping("/info/{groupProdId}")
    public ResponseEntity<GroupProd> getById(@PathVariable("groupProdId") Long groupProdId) {
        return ResponseEntity.ok(groupProdService.getById(groupProdId));
    }

    /**
     * 新增拼团活动商品表
     *
     * @param groupProd 拼团活动商品表
     * @return 是否新增成功
     */
    @SysLog("新增拼团活动商品表")
    @PostMapping
    public ResponseEntity<Boolean> save(@RequestBody @Valid GroupProd groupProd) {
        return ResponseEntity.ok(groupProdService.save(groupProd));
    }

    /**
     * 修改拼团活动商品表
     *
     * @param groupProd 拼团活动商品表
     * @return 是否修改成功
     */
    @SysLog("修改拼团活动商品表")
    @PutMapping
    public ResponseEntity<Void> updateById(@RequestBody @Valid GroupProd groupProd) {
        groupProdService.updateById(groupProd);
        // 移除缓存
        if(groupProd != null){
            groupProdService.removeGroupProdCache(groupProd.getGroupProdId());
        }
        return ResponseEntity.ok().build();
    }

    /**
     * 通过id删除拼团活动商品表
     *
     * @param groupProdId id
     * @return 是否删除成功
     */
    @SysLog("删除拼团活动商品表")
    @DeleteMapping("/{groupProdId}")
    public ResponseEntity<Boolean> removeById(@PathVariable Long groupProdId) {
        // 校验店铺
        GroupProd groupProd = groupProdService.getById(groupProdId);
        if (Objects.isNull(groupProd)) {
            // 活动商品不存在，请稍后重试
            throw new YamiShopBindException("yami.activity.prod.no.exist");
        }
        Long shopId = SecurityUtils.getShopUser().getShopId();
        if (!Objects.equals(shopId, groupProd.getShopId())) {
            //您无权对此活动商品进行操作
            throw new YamiShopBindException("yami.activity.prod.no.auth");
        }
        // 校验活动是否开始
        GroupActivity groupActivity = groupActivityService.getById(groupProd.getGroupActivityId());
        if (Objects.equals(groupActivity.getActivityStatus(), ActivityStatusEnum.UNDER_WAY.value())
                && Objects.equals(groupProd.getStatus(), GroupProdStatusEnum.NORMAL.value())) {
            // 活动进行中，不能删除活动商品，您可以等待活动结束后或失效该拼团活动后进行操作
            throw new YamiShopBindException("yami.activity.prod.cannot.delete");
        }

        // 如果活动未开始，则删除无用记录
        if (Objects.equals(groupActivity.getActivityStatus(), ActivityStatusEnum.NOT_STARTED.value())) {
            groupProdService.delGroupProd(groupProd);
        } else {
            groupProdService.updateGroupProdToDelByGroupProd(groupProd);
        }

        // 删除缓存
        productService.removeProdCacheByProdId(groupProd.getProdId(),LanguageEnum.LANGUAGE_ZH_CN.getLang());
        productService.removeProdCacheByProdId(groupProd.getProdId(), LanguageEnum.LANGUAGE_EN.getLang());
        groupProdService.removeGroupProdCache(groupProdId);
        return ResponseEntity.ok(true);
    }

    /**
     * 获取没有参与活动的活动本店铺商品
     */
    @GetMapping("/getNotGroupProdPage")
    public ResponseEntity<IPage<Product>> getNotGroupProdPage(PageParam<Product> page, ProductParam product) {
//        IPage<Product> productIPage = productService.page(page, new LambdaQueryWrapper<Product>()
//                .eq(Product::getShopId, shopId)
//                .eq(Product::getStatus, 1)
//                .eq(Objects.nonNull(product.getShopCategoryId()),Product::getShopCategoryId, product.getShopCategoryId())
//                .like(StrUtil.isNotBlank(product.getProdName()),Product::getProdName, product.getProdName())
//                .and(wrapper -> wrapper.isNull(Product::getProdType).or().eq(Product::getProdType, ProdType.PROD_TYPE_NORMAL.value()))
//                .orderByAsc(Product::getCreateTime));
        product.setLang(I18nMessage.getDbLang());
        product.setShopId(SecurityUtils.getShopUser().getShopId());
        product.setProdType(ProdType.PROD_TYPE_NORMAL.value());
        product.setStatus(ProdStatusEnums.NORMAL.getValue());
        return ResponseEntity.ok(productService.pageByLang(page,product));
    }

    @SysLog("添加拼团活动商品")
    @PostMapping("/saveByProdIds")
    public ResponseEntity<String> saveByProdIds(@RequestBody GroupProdParam groupProdParam) {
        Long shopId = SecurityUtils.getShopUser().getShopId();
        List<Long> prodIds = groupProdParam.getProdIds();
        if (CollectionUtil.isEmpty(prodIds)) {
            // 添加拼团商品不能为空
            throw new YamiShopBindException("yami.activity.add.prod.empty");
        }
        for (Long prodId : prodIds) {
            Product product = productService.getProductByProdId(prodId, I18nMessage.getDbLang());
            if (!Objects.equals(product.getShopId(), shopId)) {
                String message = I18nMessage.getMessage("yami.activity.prod.no.auth");
                throw new YamiShopBindException(message+"【" + product.getProdName() + "】");
            }
        }

        List<Long> resultIds = groupProdService.saveByProdIds(shopId, groupProdParam.getGroupActivityId(), groupProdParam.getProdIds());

        // 清理缓存
        if (CollectionUtil.isNotEmpty(resultIds)) {
            for (Long prodId : resultIds) {
                productService.removeProdCacheByProdId(prodId,LanguageEnum.LANGUAGE_ZH_CN.getLang());
                productService.removeProdCacheByProdId(prodId,LanguageEnum.LANGUAGE_EN.getLang());
            }
        }
        // 添加成功
        return ResponseEntity.ok(I18nMessage.getMessage("yami.activity.add.success"));
    }

    /**
     * 通过id查询拼团活动商品表
     *
     * @param groupProdId id
     * @return 单个数据
     */
    @GetMapping("/getGroupProdAndSkuList/{groupProdId}")
    public ResponseEntity<GroupProdAndSkuListDto> getGroupProdAndSkuListById(@PathVariable("groupProdId") Long groupProdId) {
        GroupProdAndSkuListDto groupProdAndSkuListDto = groupProdService.getGroupProdAndSkuListById(groupProdId);
        return ResponseEntity.ok(groupProdAndSkuListDto);
    }

    /**
     * 失效正在拼团中的活动商品
     */
    @SysLog("失效拼团中活动商品")
    @PutMapping("/invalid/{groupProdId}")
    public ResponseEntity<Void> invalidGroupProd(@PathVariable Long groupProdId) {
        GroupProd groupProd = groupProdService.getById(groupProdId);
        if (Objects.isNull(groupProd) || !Objects.equals(groupProd.getStatus(), GroupProdStatusEnum.NORMAL.value())) {
            // 活动商品不存在
            throw new YamiShopBindException("yami.activity.prod.no.exist");
        }
        Long shopId = SecurityUtils.getShopUser().getShopId();
        if (!Objects.equals(groupProd.getShopId(), shopId)) {
            // 您无权操作此活动
            throw new YamiShopBindException("yami.activity.no.auth");
        }
        // 查看活动
        ApiGroupActivityDto apiGroupActivityInfo = groupActivityService.getApiGroupActivityInfo(groupProd.getGroupActivityId(), groupProd.getProdId());
        if (Objects.isNull(apiGroupActivityInfo) || !Objects.equals(apiGroupActivityInfo.getActivityStatus(), ActivityStatusEnum.UNDER_WAY.value())) {
            // 未找到此活动，请稍后重试
            throw new YamiShopBindException("yami.activity.cannot.find");

        }
        groupProdService.invalidGroupProd(groupProd);

        productService.removeProdCacheByProdId(groupProd.getProdId(),LanguageEnum.LANGUAGE_ZH_CN.getLang());
        productService.removeProdCacheByProdId(groupProd.getProdId(),LanguageEnum.LANGUAGE_EN.getLang());
        groupProdService.removeGroupProdCache(groupProdId);
        return ResponseEntity.ok().build();
    }

}
